import { LeftOutlined } from '@ant-design/icons';
import { Progress, Tabs, Typography } from 'antd';
import React from 'react';
import { TaskDetailInfo } from 'admin/schema/Task';
import { getTaskDetail } from 'admin/servers/servers';
import { getCallModeName, getStatusName } from '../components/TaskTool';
import CallAnalysis from './CallAnalysis';
import { CallRecord } from './CallRecord';
import CallResult from './CallResult';
import { ManualListen } from './ManualListen/index2';
import qs from 'query-string';
import { getSocket } from 'servers/socket';
import { JSONObject } from 'admin/schema/common';
import { CallTaskCountMsg } from 'admin/schema/SocketMessage';
import CallStrategy from './CallStrategy';
import { getTimeByMin } from 'utils/tools';
import { getStore } from 'store/store';
import './style.scss';
import CallRules from './CallRules';
const { TabPane } = Tabs;
const { Text } = Typography;

interface TaskDetailProps {}

interface TaskDetailState {
  listData: TaskDetailInfo;
}
/**
 * 任务管理-任务详情
 */
export default class TaskDetail extends React.Component<{}, TaskDetailState> {
  private taskId: number;
  /**tab的key值 */
  private idx: string;
  constructor(prop: {}) {
    super(prop);
    this.idx = qs.parse((this.props as any).location.search).type as string;
    console.log('初始化--1', this.idx);
    this.taskId = parseInt(qs.parse((this.props as any).location.search).id as string);
    this.state = {
      listData: {} as TaskDetailInfo,
    };
  }

  componentDidMount() {
    this.addSocketEvent();
    this.fetchData();
  }

  componentDidUpdate() {
    this.taskId = parseInt(qs.parse((this.props as any).location.search).id as string);
  }
  componentWillUnmount = () => {
    this.removeSocketEvent();
    this.setState = (state, callback) => {
      return;
    };
  };
  private addSocketEvent() {
    getSocket().addEvent('callTaskStatusBroadcastEvent', (data: JSONObject) => {
      // console.log(`任务详情-推送消息-接收--`, data);
      const { listData } = this.state;
      if (data.taskId !== this.taskId.toString()) {
        return;
      }
      setTimeout(() => {
        // console.log(`任务ID【${this.taskId}】--任务详情-推送消息-接收--`, data);
        data = data as CallTaskCountMsg;
        // console.log(listData, "原始的");
        const copyDetailData = listData;
        // 接收的数据，有状态，就更新
        if (data.taskStatus) {
          copyDetailData.taskStatus = data.taskStatus;
        }
        copyDetailData.totalNum = data.countTotal;
        copyDetailData.finishedNum = data.countComplete;
        copyDetailData.restTime = data.estimateCompleteTime;
        // console.log(copyDetailData, "更新的数据-去上屏");
        this.setState({
          listData: copyDetailData,
        });
      }, 0);
    });
  }
  /** 卸载socket事件*/
  private removeSocketEvent() {
    console.log('任务详情-推送消息->>>>socket事件-删除');
    const socket = getSocket();
    socket.removeEvent(['callTaskStatusBroadcastEvent']);
  }

  /**请求数据 */
  private fetchData() {
    // debugger
    getTaskDetail(this.taskId).then(taskDetailRes => {
      this.setState({
        listData: taskDetailRes.data,
      });
      const { finishedNum } = taskDetailRes.data;
      getStore().set('currentTaskFinishedNum', finishedNum);
    });
  }

  /**
   * 返回任务列表页
   */
  private goBack = () => {
    (this.props as JSONObject).history.push('/webapp/outbound/task/callTask');
  };

  /**
   * 提取计算完成比例
   */
  private getPrecent(data: TaskDetailInfo) {
    return Math.floor((data.totalNum ? data.finishedNum / data.totalNum : 0) * 100);
  }

  render() {
    const { taskId, idx } = this;
    const history = (this.props as any).history;
    const { listData } = this.state;
    // 未呼数
    const leftNum = listData.totalNum - listData.finishedNum;

    return (
      <div className="taskdetail">
        <div className="taskdetail-header">
          <span
            className="left"
            style={{ color: '#1890ff', cursor: 'pointer' }}
            onClick={this.goBack.bind(this)}
          >
            <LeftOutlined /> 返回
          </span>
          <span style={{ fontWeight: 'bold', marginLeft: '20px' }}>任务详情</span>
        </div>
        <div className="taskdetail-body">
          <div className="taskdetail-body-list">
            <div className="task-detail-item">
              <span className="taskdetail-item-label">任务名称</span>
              <span className="taskdetail-item-val" title={listData.taskName}>
                <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                  {listData.taskName}
                </Text>
              </span>
            </div>
            <div className="task-detail-item">
              <span className="taskdetail-item-label">任务类型</span>
              <span className="taskdetail-item-val">
                {listData.flowType === 0 && '机器人任务'}
                {listData.flowType === 1 && '通知流程任务'}
                {listData.flowType === 2 && '人机协同任务'}
                {listData.flowType === 3 && '人工自动外呼任务'}
              </span>
            </div>
            <div className="task-detail-item">
              <span className="taskdetail-item-label">任务状态</span>
              <span className="taskdetail-item-val color_blue">
                {getStatusName(listData.taskStatus)}
              </span>
            </div>
            {listData.flowType === 3 && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">呼叫模式</span>
                <span className="taskdetail-item-val">{getCallModeName(listData.callMode)}</span>
              </div>
            )}
            {listData.flowName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">
                  {listData.flowType === 1 ? '通知流程' : '机器人名称'}
                </span>
                <span className="taskdetail-item-val" title={listData.flowName}>
                  <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                    {listData.flowName}
                  </Text>
                </span>
              </div>
            )}
            <div className="task-detail-item">
              <span className="taskdetail-item-label">号码组</span>
              <span className="taskdetail-item-val" title={listData.flowName}>
                <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                  {listData.callGroupName}
                </Text>
              </span>
            </div>
            {listData.maxCall && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">外呼并发数</span>
                <span className="taskdetail-item-val">{listData.maxCall}</span>
              </div>
            )}
            {listData.seatsGroupName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">执行坐席组</span>
                <span className="taskdetail-item-val">{listData.seatsGroupName}</span>
              </div>
            )}
            {listData.maxSeatsSession && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">最大弹屏数</span>
                <span className="taskdetail-item-val">{listData.maxSeatsSession}</span>
              </div>
            )}
            <div className="task-detail-item">
              <span className="taskdetail-item-label">创建人</span>
              <span className="taskdetail-item-val">{listData.userName}</span>
            </div>
            {listData.mrcpName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">语音识别</span>
                <span className="taskdetail-item-val" title={listData.mrcpName}>
                  <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                    {listData.mrcpName}
                  </Text>
                </span>
              </div>
            )}
            {listData.soundRecordTemplateName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">录音</span>
                <span className="taskdetail-item-val" title={listData.soundRecordTemplateName}>
                  <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                    {listData.soundRecordTemplateName}
                  </Text>
                </span>
              </div>
            )}
            {listData.ttsName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">TTS</span>
                <span className="taskdetail-item-val" title={listData.ttsName}>
                  <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                    {listData.ttsName}
                  </Text>
                </span>
              </div>
            )}
            <div className="task-detail-item">
              <span className="taskdetail-item-label">黑名单</span>
              <span className="taskdetail-item-val">{listData.blackSwitch ? '开启' : '关闭'}</span>
            </div>
            {listData.beforeCallSmsTempName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">呼前短信</span>
                <span className="taskdetail-item-val" title={listData.beforeCallSmsTempName}>
                  <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                    {listData.beforeCallSmsTempName}
                  </Text>
                </span>
              </div>
            )}
            {listData.sysAnswerByeTempName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">呼通挂机短信</span>
                <span className="taskdetail-item-val" title={listData.sysAnswerByeTempName}>
                  <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                    {listData.sysAnswerByeTempName}
                  </Text>
                </span>
              </div>
            )}
            {listData.sysNoanswerByeTempName && (
              <div className="task-detail-item">
                <span className="taskdetail-item-label">未呼通挂机短信</span>
                <span className="taskdetail-item-val" title={listData.sysNoanswerByeTempName}>
                  <Text style={{ width: 'calc(100% - 120px)' }} ellipsis>
                    {listData.sysNoanswerByeTempName}
                  </Text>
                </span>
              </div>
            )}
            <div className="task-detail-item">
              <span className="taskdetail-item-label">任务描述</span>
              <span className="taskdetail-item-val">{listData.taskDesc}</span>
            </div>
          </div>
          <div className="taskdetail-body-graph">
            <div className="taskdetail-body-graph-info">
              <div>总数&nbsp;&nbsp;{listData.totalNum}</div>
              <div className="color_blue">已呼数&nbsp;&nbsp;{listData.finishedNum}</div>
              <div>未呼数&nbsp;&nbsp;{leftNum}</div>
              {listData.totalNum > 0 && leftNum > 0 && !listData.restTime && <div>--</div>}
              {listData.totalNum > 0 && leftNum > 0 && listData.restTime > 0 && (
                <div className="color_green">预计{getTimeByMin(listData.restTime)}后完成</div>
              )}
              {listData.totalNum > 0 && leftNum === 0 && <div className="color_green">已完成</div>}
              {listData.totalNum === 0 && <div>--</div>}
            </div>
            <div className="taskdetail-body-graph-circle">
              <Progress type="circle" percent={this.getPrecent(listData)} width={100} />
            </div>
          </div>
        </div>
        {listData.flowType >= 0 && (
          <Tabs
            type="card"
            defaultActiveKey={idx}
            onChange={activeKey => {
              history.push(`/webapp/outbound/task/callTask/detail?id=${taskId}&type=${activeKey}`);
            }}
          >
            {listData.flowType === 0 && (
              // 只有【机器人任务】-人工监听
              <TabPane tab="人工监听" key="manual">
                <ManualListen taskId={taskId} />
              </TabPane>
            )}
            <TabPane tab="呼叫规则" key="rules">
              <CallRules formData={listData} />
            </TabPane>
            <TabPane tab="呼叫结果" key="result">
              <CallResult taskId={taskId} />
            </TabPane>
            <TabPane tab="通话记录" key="record">
              <CallRecord taskId={taskId} repeatTimes={listData.repeatCallTimes} />
            </TabPane>
            <TabPane tab="通话分析" key="analysis">
              <CallAnalysis taskId={taskId} />
            </TabPane>
            <TabPane tab="重呼策略" key="strategy">
              <CallStrategy taskId={taskId} />
            </TabPane>
          </Tabs>
        )}{' '}
      </div>
    );
  }
}
